package com.zeroxml.cms.service.impl;

import com.zeroxml.cms.service.ISiteConfigService;
import com.zeroxml.cms.bo.SiteConfig;
import com.thoughtworks.xstream.XStream;

import java.io.*;

/**
 * User: cjp
 * Date: 2007-9-20
 * Time: 14:44:51
 */
public class SiteConfigService extends BaseService implements ISiteConfigService {
    String cacheName="siteConfig";
    private String configPath;

    public void setConfigPath(String configPath) {
        this.configPath = configPath;
    }

    public SiteConfig getSiteConfig() {
        SiteConfig siteConfig = (SiteConfig) cache.get(cacheName);
        if (siteConfig == null) {
            siteConfig = new SiteConfig();
            XStream xStream = new XStream();
            xStream.alias("siteConfig", SiteConfig.class);
            BufferedReader reader;
            try {
                reader = new BufferedReader(new InputStreamReader(new FileInputStream(configPath), "UTF-8"));
                siteConfig = (SiteConfig) xStream.fromXML(reader);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            cache.put(cacheName,siteConfig);
        }
        return siteConfig;
    }

    public void refreshSiteConfig(SiteConfig siteConfig) {
        XStream xStream = new XStream();
        xStream.alias("siteConfig", SiteConfig.class);
        StringBuffer sb = new StringBuffer();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        sb.append(xStream.toXML(siteConfig));
        try {
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(configPath), "UTF-8"));
            out.write(sb.toString());
            out.flush();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        cache.remove(cacheName);
    }
}
